<template>
  <div class="reply-item flex">
    <!-- 左侧头像 -->
    <div class="left-avatar mr-2" style="">
      <UserAvatar
        :image-url="replyItem.UserAvatar"
        :data-user-id="replyItem.UserID"
        class="cursor-pointer"
        size="small"
      />
    </div>

    <div class="right-main flex-1 flex flex-col overflow-hidden">
      <!-- 回复顶部信息 -->
      <div
        class="flex justify-between teld-color-gray"
        :class="[dense || true ? 'mb-1' : 'mb-2']"
      >
        <div class="flex items-center">
          <span class="teld-color-gray font-semibold">{{
            userNameDisplay
          }}</span>
          <SvgTriangle
            v-if="replyItem.RespondedUserID"
            width="8"
            height="8"
            class="mx-2"
          />
          <span
            v-if="replyItem.RespondedUserID"
            class="teld-color-gray font-semibold"
            >{{ replyItem.RespondedUserName }}</span
          >
        </div>
        <!-- <span :title="replyItem.ReplyTime" class="teld-color-gray">{{
          replyItem.ReplyTimeRelative
        }}</span> -->
      </div>

      <!-- 回复内容行 -->
      <div
        class="reply-content break-all"
        :class="[dense || true ? 'mb-1' : 'mb-2']"
      >
        <div
          v-if="!replyItem.IsDeleted"
          v-html="decodeURIComponent(replyItem.Content)"
          @click="onClickContent"
        ></div>
        <div v-else class="teld-color-gray">
          {{ /*该条评论回复已删除*/ qLangComment.replyIsDeleted }}
        </div>
      </div>

      <!-- 附件 -->
      <section
        v-if="
          !replyItem.IsDeleted &&
          replyItem.Attachments &&
          replyItem.Attachments.length
        "
        class="attachments-section w-full"
        :class="[dense ? 'mb-1' : 'mb-2']"
      >
        <div
          v-for="attachment in replyItem.Attachments"
          :key="attachment.ID"
          class="attachment-file flex items-center"
          :class="[dense ? '' : 'py-1']"
          @click="onClickAttachment(attachment)"
        >
          <!-- 文件类型图标 -->
          <FileTypeIcon :file-name="attachment.FileName" class="w-6 h-6 mr-2" />
          <!-- 文件名 -->
          <div
            class="flex-1 mr-2 truncate text-xs overflow-hidden"
            :title="attachment.FileName"
          >
            {{ attachment.FileName }}
          </div>
        </div>
      </section>

      <!-- 回复底部按钮行 -->
      <div v-if="!replyItem.IsDeleted" class="flex justify-between">
        <!-- 相对时间 -->
        <span :title="replyItem.ReplyTime" class="teld-color-gray">{{
          replyItem.ReplyTimeRelative
        }}</span>
        <div
          class="reply-operations flex justify-end"
          :class="[disabled ? 'teld-color-lightgray' : 'teld-color-gray']"
        >
          <!-- 点赞 -->
          <div
            class="reply-like flex rounded-sm leading-5 hover:text-theme-color"
            :class="[disabled ? 'cursor-not-allowed' : 'cursor-pointer']"
            @click="onClickLike"
          >
            <SvgHeartFilled v-show="replyItem.Liked" class="mr-1" />
            <SvgHeart v-show="!replyItem.Liked" class="mr-1" />
            <span class="">{{ replyItem.LikeCount || 0 }}</span>
          </div>
          <!-- 收藏 -->
          <div
            class="reply-star flex ml-2 rounded-sm leading-5 hover:text-theme-color hidden"
            :class="[disabled ? 'cursor-not-allowed' : 'cursor-pointer']"
            @click="onClickFavorite"
          >
            <SvgStarFilled v-show="replyItem.IsFavorite" class="mr-1" />
            <SvgStar v-show="!replyItem.IsFavorite" class="mr-1" />
            <span class="">
              {{ replyItem.FavoriteCount || 0 }}
            </span>
          </div>
          <!-- 回复 -->
          <div
            class="reply-reply ml-2 rounded-sm hover:text-theme-color"
            :class="[
              disabled ? 'cursor-not-allowed' : 'cursor-pointer',
              inputVisible ? 'teld-theme-color' : 'teld-color-gray',
            ]"
            @click="onClickReply"
            >回复</div
          >
          <!-- 删除 -->
          <div
            v-if="replyItem.CanCancel && !disabled"
            class="reply-revoke ml-2 rounded-sm hover:text-theme-color"
            @click="onClickRevoke"
          >
            {{ qLangComment.delete }}
          </div>
        </div>
      </div>

      <!-- 评论的回复框 -->
      <draft-editor
        ref="draftEditorRef"
        v-model:visible="inputVisible"
        :placeholder="inputPlaceholder"
        class="h-0"
        @comment="onReplyToReply"
      />
    </div>

    <!-- <PersonnelInfoPopup
      v-model:visible="personnelInfoVisible"
      v-model:user-id="mentionedUserId"
    /> -->

    <!-- 大图查看 -->
    <t-image-preview
      ref="imagePreviewRef"
      v-model="currentImgSrc"
      :src-list="previewSrcList"
    ></t-image-preview>
  </div>
</template>

<script>
// Components
import SvgHeart from '../../components/svg-icons/heart.vue';
import SvgHeartFilled from '../../components/svg-icons/heart-filled.vue';
import SvgStar from '../../components/svg-icons/star.vue';
import SvgStarFilled from '../../components/svg-icons/star-filled.vue';
import SvgTriangle from '../../components/svg-icons/triangle.vue';
import DraftEditor from '../draft-editor/index.vue';
import UserAvatar from '../../components/user-avatar/index.vue';
import FileTypeIcon from '../../components/file-type-icon/index.vue';
// import PersonnelInfoPopup from '../personnel-info-popup/index.vue';

// Utils
import { useRelativeTime, saveAs } from '../../hooks';
import dayjs from 'dayjs';
import {
  saveReply,
  deleteReply,
  turnOnLike,
  cancelLike,
} from '../../hooks/api.js';

export default {
  name: 'TmReplyItem',
  inject: [
    'loginUserInfo',
    // 'pageUrl',
    'notificationLink',
    'qLangComment',
    'dense',
  ],
  props: {
    /**
     * Reply数据条目
     */
    dataItem: {
      type: Object,
      default: () => {},
    },
    total: {
      type: Number,
      default: 0,
    },
    isCommentDeleted: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    SvgHeart,
    SvgHeartFilled,
    SvgStar,
    SvgStarFilled,
    SvgTriangle,
    DraftEditor,
    // RevokePopover,
    UserAvatar,
    FileTypeIcon,
    // PersonnelInfoPopup,
  },
  data() {
    return {
      // isLoading: true,
      inputVisible: false,
      replyItem: {},
      revokeConfirmVisible: false,
      //
      personnelInfoVisible: false,
      mentionedUserId: null,
      //
      previewSrcList: [],
      currentImgSrc: '',
      //
      deleteConfirmVisible: false,
    };
  },
  computed: {
    disabled() {
      return this.isCommentDeleted || this.replyItem.IsDeleted;
    },
    showReplyTo() {
      // TODO
      return true;
    },
    isAuthor() {
      const loginUser = this.loginUserInfo;
      return loginUser.userId === this.replyItem.UserID;
    },
    userNameDisplay() {
      return this.isAuthor ? this.qLangComment.me : this.replyItem.UserName;
    },
    inputPlaceholder() {
      return `${this.qLangComment.reply} ${this.userNameDisplay}`;
    },
  },
  created() {
    const { ReplyTime } = this.dataItem;
    const timeRelative = useRelativeTime(this.$q.lang.relativeTime)(ReplyTime);
    this.replyItem = {
      ...this.dataItem,
      ReplyTime: dayjs(ReplyTime).format('YYYY/MM/DD HH:mm:ss'),
      ReplyTimeRelative: timeRelative || '',
    };
  },
  methods: {
    async onClickLike() {
      if (this.disabled) return;
      const isLike = (this.replyItem.Liked = !this.replyItem.Liked);
      const diff = this.replyItem.Liked ? 1 : -1;
      this.replyItem.LikeCount += diff;
      let succeeded = false;

      const payload = isLike
        ? { CommentID: this.replyItem.CommentID, TargetID: this.replyItem.ID }
        : { Id: this.replyItem.CommentID, TargetID: this.replyItem.ID };
      const updateLikeState = isLike ? turnOnLike : cancelLike;
      try {
        const res = await updateLikeState(payload);

        if (!res || res.state !== '1') {
          return;
        }

        succeeded = true;
        // this.$TM.Toast(isLike ? '已点赞' : '已取消点赞');
      } catch (error) {
        console.log(error);
      } finally {
        // 接口调用失败后，页面状态回滚
        if (!succeeded) {
          this.replyItem.Liked = !isLike;
          this.replyItem.LikeCount -= diff;
        }
      }
    },
    async onClickFavorite() {
      if (this.disabled) return;
      this.replyItem.IsFavorite = !this.replyItem.IsFavorite;
      const diff = this.replyItem.IsFavorite ? 1 : -1;
      this.replyItem.FavoriteCount += diff;
    },
    onClickReply() {
      if (this.disabled) return;
      this.inputVisible = true;
    },
    /** TODO 使用自定义的RevokeConfirm组件时用 */
    toggleRevokeConfirm() {
      this.revokeConfirmVisible = !this.revokeConfirmVisible;
    },
    async handleDeleteReply() {
      this.replyItem.IsDeleted = true;
      const onFail = () => {
        this.replyItem.IsDeleted = false;
        this.replyItem.CanCancel = false;
        // this.$TM.Toast('删除失败');
        this.$q.notify(this.qLangComment.deleteFailed);
      };

      try {
        // const { data } = await this.$utils.sgApi.getDataAsync({
        //   url: this.$utils.common.getServiceUrl('CMTS-CancelReply'),
        //   data: { id: this.replyItem.ID },
        // });
        const res = await deleteReply(this.replyItem.ID);

        if (!res || res.state !== '1') {
          onFail();
          return;
        }
        // this.$TM.Toast('已删除');
        this.$q.notify(this.qLangComment.deleteDone);
        this.$emit('delete', this.replyItem);
      } catch (error) {
        console.log(error);
        onFail();
      }
    },
    async onClickRevoke() {
      if (this.disabled) return;

      this.$q
        .dialog({
          title: this.qLangComment.confirmation,
          message: this.qLangComment.deleteConfirmation,
          cancel: true,
          persistent: true,
        })
        .onOk(() => {
          console.log('>>>> OK');
          this.handleDeleteReply();
        })
        .onCancel(() => {
          console.log('>>>> Cancel');
        });
    },
    async onReplyToReply(draftInfo) {
      const loginUser = this.loginUserInfo;
      const { content, fileList, onSucceed, onFail } = draftInfo;
      const newCommentReply = {
        // 接口必传字段：
        CommentID: this.replyItem.CommentID,
        Content: content,
        UserAvatar: loginUser.avatar,
        // RespondedUserID: this.replyItem.UserID,
        // RespondedUserName: this.replyItem.UserName,
        TargetID: this.replyItem.ID,
        Attachments: fileList.map(n => n.result),
        Url: this.notificationLink(),
        UrlParams: JSON.stringify({
          // fpath: encodeURIComponent(this.pageUrl),
          showComment: true,
          commentId: this.replyItem.CommentID,
        }),
      };
      // 回复给
      if (loginUser.userId !== this.replyItem.UserID) {
        newCommentReply.RespondedUserID = this.replyItem.UserID;
        newCommentReply.RespondedUserName = this.replyItem.UserName;
      }

      try {
        const res = await saveReply(newCommentReply);
        console.log('SaveReply', res);
        if (!res || res.state !== '1' || !res.data) {
          onFail();
          return;
        }

        // mock new record, and override with real data
        Object.assign(
          newCommentReply,
          {
            ID: 'comment-reply-m-' + parseInt(Math.random() * 1000),
            ReplyTime: Date().toLocaleString(),
            UserID: loginUser.userId,
            UserName: loginUser.userName,
            Liked: false,
            LikeCount: 0,
            IsFavorite: false,
            FavoriteCount: 0,
            IsDeleted: false,
            CanCancel: true,
          },
          res.data,
        );

        // 调接口成功后清空输入框内容
        onSucceed();
        this.inputVisible = false;
        // 评论完将新添加评论展示出来
        this.$emit('reply', newCommentReply);
      } catch (error) {
        console.log(error);
        onFail();
      }
    },
    onClickContent(e) {
      const el = e.target;
      // 如果点击了图片，则放大查看
      if (el.nodeName === 'IMG' && el.currentSrc) {
        // this.$TM.ImagePreview({images:[el.currentSrc]});
        const previwer = this.$refs.imagePreviewRef;
        if (previwer) {
          previwer.open(el.currentSrc);
        }
      } else if (el.dataset.userId) {
        // 点击了提及人，则弹出人员信息
        this.mentionedUserId = el.dataset.userId;
        this.personnelInfoVisible = true;
      } else {
        // 点击了内容，则直接弹出回复框
        this.onClickReply();
      }
    },
    handleDownloadFile(attachment) {
      const { AttachmentUrl, FileName } = attachment;
      saveAs({
        url: AttachmentUrl,
        fileName: FileName,
      });
    },
    onClickAttachment(attachment) {
      const ext = attachment.FileName.split('.').pop().toLowerCase();
      const previwer = this.$refs.imagePreviewRef;
      if (['png', 'jpg', 'jpeg', 'gif'].includes(ext) && previwer) {
        previwer.open(attachment.AttachmentUrl);
        return;
      }
      this.handleDownloadFile(attachment);
    },
  },
};
</script>

<style lang="scss" scoped></style>
